package com.bw.lib_storage.mmkv

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class MMKVProperty<T>(private val defaultValue: T): ReadWriteProperty<MMKVOwner, T> {
    override fun getValue(thisRef: MMKVOwner, property: KProperty<*>): T {
        return thisRef.mmkv.run{
            when(defaultValue){
                is String -> getString(property.name, defaultValue)
                is Int -> getInt(property.name, defaultValue)
                is Boolean -> getBoolean(property.name, defaultValue)
                is Float -> getFloat(property.name, defaultValue)
                is Long -> getLong(property.name, defaultValue)
                is Double -> decodeDouble(property.name, defaultValue)
                else -> Unit
            }as T
        }

    }

    override fun setValue(thisRef: MMKVOwner, property: KProperty<*>, value: T) {
        thisRef.mmkv.run{
            when(value){
                is String -> getString(property.name, value)
                is Int -> getInt(property.name, value)
                is Boolean -> getBoolean(property.name, value)
                is Float -> getFloat(property.name, value)
                is Long -> getLong(property.name, value)
                is Double -> decodeDouble(property.name, value)
                else -> Unit
            }
        }
    }
}